package com.stormrage.edu.ctrl.learn;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.stormrage.edu.serv.edu.EduCourseServ;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.learn.LeaStudentCourseServ;
import com.stormrage.edu.serv.learn.LeaStudentSelectServ;
import com.stormrage.edu.serv.learn.LeaStudentServ;
import com.stormrage.edu.serv.learn.LeaTermNessServ;
import com.stormrage.edu.serv.learn.LeaTermServ;
import com.stormrage.edu.serv.student.StuAcctServ;
import com.stormrage.entity.edu.rep.EduCourseRep;
import com.stormrage.entity.learn.LeaStudent;
import com.stormrage.entity.learn.LeaStudentSelect;
import com.stormrage.entity.learn.LeaTerm;
import com.stormrage.entity.learn.LeaTermNess;
import com.stormrage.entity.learn.rep.LeaMajorStudyRep;
import com.stormrage.entity.learn.rep.LeaStuSelectRep;
import com.stormrage.entity.learn.req.LeaMajorSelectReq;
import com.stormrage.entity.learn.req.LeaSelectReq;
import com.stormrage.entity.learn.req.LeaStudentReq;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.student.StuAcct;
import com.stormragetech.core.ctrl.BaseCtrl;

/**
 * @Title: LeaStudyCtrl.java
 * @Package com.stormrage.edu.ctrl.learn
 * @Description: 选课 Controller
 * @author www.stormragetech.com
 * @date 2016年5月11日
 * @version V1.0
 */
@Controller
@RequestMapping("/select")
public class LeaSelectCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(LeaSelectCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['html.logo']}")
	private String htmlLogo;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Autowired
	private EduCourseServ eduCourseServ;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private LeaStudentServ leaStudentServ;

	@Autowired
	private LeaStudentCourseServ leaStudentCourseServ;

	@Autowired
	private LeaStudentSelectServ leaStudentSelectServ;

	@Autowired
	private LeaTermServ leaTermServ;

	@Autowired
	private LeaTermNessServ leaTermNessServ;

	@Autowired
	private StuAcctServ stuAcctServ;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String index(Model model) throws UnsupportedEncodingException {

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 Index 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ Controller 操作 ------------------
			LeaMajorSelectReq req = LeaMajorSelectReq.instance(curr.getId(), 0);
			List<LeaMajorStudyRep> array = eduMajorServ.queryListForSelect(req);

			// ------------------ Model 赋值 ------------------
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);
			model.addAttribute("data", array);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 Index 】-【 GET 】-【 COMPLETED 】");
		return "select/index";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String select(@PathVariable("id") Integer id, Model model, RedirectAttributes redirect)
			throws UnsupportedEncodingException {

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 select 】-【 GET 】-【 STARTED 】");

		try {

			// ------------------ 获取用户信息 ------------------
			Subject currentUser = SecurityUtils.getSubject();
			StuAcct curr = stuAcctServ.queryByAcct(currentUser.getPrincipal().toString());

			// ------------------ Controller 操作 ------------------
			LeaTerm ter = leaTermServ.queryById(id);
			List<EduCourseRep> array = eduCourseServ.queryRepListForSelect(ter.getMajorId());
			LeaTermNess term = leaTermNessServ.queryByTermId(id);

			LeaStudentReq req = LeaStudentReq.instance(curr.getId(), id, ter.getMajorId());
			LeaStudent stu = leaStudentServ.queryByAcctMajor(req);

			LeaStudentSelect select = leaStudentSelectServ.queryByStuId(stu.getId());
			if (null != null && select.getSelected().equals(1)) {
				ErrorRep err = ErrorRep.instance(true, "您已完成选课，请直接学习");
				redirect.addFlashAttribute("err", err);
				return "redirect:/result";
			}

			LeaStuSelectRep rep = LeaStuSelectRep.instance(stu.getId(), term.getNess());

			// ------------------ Model 赋值 ------------------
			model.addAttribute("ipath", rootUrl + imagePath);
			model.addAttribute("user", curr);
			model.addAttribute("array", array);
			model.addAttribute("data", rep);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 select 】-【 GET 】-【 COMPLETED 】");
		return "select/select";
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.POST)
	public String select(@PathVariable("id") Integer id, LeaSelectReq req,
			@RequestParam(value = "course", required = false) String[] course, RedirectAttributes redirect)
			throws UnsupportedEncodingException {

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 select 】-【 POST 】-【 STARTED 】");

		logger.debug(" 选课为 " + course);

		ErrorRep err = null;
		String errMsg = "";

		try {

			if (null == course) {
				errMsg = "选择课程数量不正确，您选择的数量为【 0 】，正确数量为【 " + req.getCount() + " 】";
				err = ErrorRep.instance(false, errMsg);
				redirect.addFlashAttribute("err", err);
				return "redirect:/select/{id}";
			}

			if (!req.getCount().equals(course.length)) {
				errMsg = "选择课程数量不正确，您选择的数量为【" + course.length + "】，正确数量为【" + req.getCount() + "】";
				err = ErrorRep.instance(false, errMsg);
				redirect.addFlashAttribute("err", err);
				return "redirect:/select/{id}";
			}

			// ------------------ Controller 操作 ------------------
			req = LeaSelectReq.instance(req, id, course);
			leaStudentCourseServ.select(req);

			errMsg = "选择课程成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "选择课程发生异常";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/select/{id}";
		}

		logger.debug("【 Controller 】-【 LeaSelectCtrl 】-【 select 】-【 POST 】-【 COMPLETED 】");
		return "redirect:/result";
	}

}
